package com.eastfair.venuebooking.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.common.vo.AttachmentFileVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.pay.api.AttachmentFileFeign;
import com.eastfair.venuebooking.dto.*;
import com.eastfair.venuebooking.entity.ExhibitionMaterial;
import com.eastfair.venuebooking.entity.MaterialDeclaration;
import com.eastfair.venuebooking.enums.VenueBookingMoudleEnum;
import com.eastfair.venuebooking.service.ExhibitionMaterialService;
import com.eastfair.venuebooking.service.MaterialDeclarationService;
import com.eastfair.venuebooking.vo.ExhibitionMaterialVO;
import com.eastfair.venuebooking.vo.MaterialDeclarationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 材料申报
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/materialDeclaration")
@Api(value = "MaterialDeclaration", tags = "材料申报")
@PreAuth(replace = "venuebooking:materialDeclaration:")
public class MaterialDeclarationController extends SuperController<MaterialDeclarationService, Long, MaterialDeclaration, MaterialDeclarationPageQuery, MaterialDeclarationSaveDTO, MaterialDeclarationUpdateDTO> {

    @Autowired
    private EchoService echoService;
    @Resource
    private AttachmentFileFeign attachmentFileFeign;
    @Resource
    private ExhibitionMaterialService exhibitionMaterialService;

    @Override
    public void handlerResult(IPage<MaterialDeclaration> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<MaterialDeclaration> materialDeclarationList = list.stream().map((map) -> {
            MaterialDeclaration materialDeclaration = MaterialDeclaration.builder().build();
            //TODO 请在这里完成转换
            return materialDeclaration;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(materialDeclarationList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<MaterialDeclarationPageQuery> params) {
        MaterialDeclarationPageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 添加申报材料
     *
     * @param materialDeclarationSaveDTO 添加申报材料
     * @return
     */
    @ApiOperation(value = "添加申报材料", notes = "添加申报材料")
    @SysLog("添加申报材料")
    @PostMapping("/addMaterialDeclaration")
    public R addMaterialDeclaration(@RequestBody @Validated(MaterialDeclarationDTO.Check.class) MaterialDeclarationDTO materialDeclarationSaveDTO) {
        log.info("addMaterialDeclaration - 添加申报材料   materialDeclarationSaveDTO: {}",materialDeclarationSaveDTO);
        return success(baseService.addMaterialDeclaration(materialDeclarationSaveDTO));
    }

    /**
     * 修改申报材料
     *
     * @param materialDeclarationUpdateDTO 修改申报材料
     * @return
     */
    @ApiOperation(value = "修改申报材料", notes = "修改申报材料")
    @SysLog("修改申报材料")
    @PostMapping("/updateMaterialDeclaration")
    public R updateMaterialDeclaration(@RequestBody @Validated({MaterialDeclarationDTO.Check.class,SuperEntity.Update.class}) MaterialDeclarationDTO materialDeclarationUpdateDTO) {
        log.info("updateMaterialDeclaration - 修改申报材料   materialDeclarationUpdateDTO: {}",materialDeclarationUpdateDTO);
        return success(baseService.updateMaterialDeclaration(materialDeclarationUpdateDTO));
    }

    /**
     * 删除申报材料
     *
     * @param id 删除申报材料
     * @return
     */
    @ApiOperation(value = "删除申报材料", notes = "删除申报材料")
    @SysLog("删除申报材料")
    @GetMapping("/delMaterialDeclaration")
    public R delMaterialDeclaration(@RequestParam("id") @Validated @NotNull(message = "申报材料ID必填") Long id) {
        log.info("delMaterialDeclaration - 删除申报材料   id: {}",id);
        MaterialDeclaration materialDeclaration = new MaterialDeclaration();
        materialDeclaration.setId(id);
        materialDeclaration.setIsDeleted(BusinessConstant.YES);
        return success(baseService.updateById(materialDeclaration));
    }

    /**
     * 修改模版
     *
     * @param attachmentFileDTO 修改模版
     * @return
     */
    @ApiOperation(value = "修改模版", notes = "修改模版")
    @SysLog("修改模版")
    @PostMapping("/updateAttachmentFile")
    @Transactional(rollbackFor = Exception.class)
    public Object updateAttachmentFile(@RequestBody AttachmentFileDTO attachmentFileDTO) {
        log.info("updateAttachmentFile - 修改模版   attachmentFileDTO: {}",attachmentFileDTO);
        MaterialDeclaration materialDeclaration = baseService.getById(attachmentFileDTO.getBusinessId());
        if(Objects.nonNull(materialDeclaration)){
            MaterialDeclaration updateEntity = new MaterialDeclaration();
            updateEntity.setAttamentUrl(attachmentFileDTO.getAttachmentUrl());
            baseService.updateById(updateEntity);
        }
        attachmentFileDTO.setBusinessType(VenueBookingMoudleEnum.MATERIAL_DECLARATION.getCode());
        return attachmentFileFeign.addAttachmentFile(Collections.singletonList(attachmentFileDTO));
    }

    /**
     * 申报材料列表
     * @param params
     * @return
     */
    @ApiOperation(value = "申报材料列表", notes = "申报材料列表")
    @PostMapping("/queryMaterialDeclaration")
    public R<IPage<MaterialDeclarationVO>> queryMaterialDeclaration(@RequestBody PageParams<MaterialDeclarationQuery> params) {
        log.info("queryMaterialDeclaration - 申报材料列表   params: {}",params);
        return R.success(baseService.queryMaterialDeclaration(params));
    }

    /**
     * 通过展会id查询材料申报记录
     * @param exhibitionId
     * @return
     */
    @ApiOperation(value = "通过展会id查询材料申报记录", notes = "通过展会id查询材料申报记录")
    @GetMapping("/queryExhibitionMaterialByExhibitionId")
    public R<List<ExhibitionMaterialVO>> queryExhibitionMaterialByExhibitionId(@RequestParam("exhibitionId") @Validated @NotNull(message = "展会ID必填") Long exhibitionId,@RequestParam(name="id",required = false) Long id) {
        log.info("queryExhibitionMaterialByExhibitionId - 通过展会id查询材料申报记录   exhibitionId: {}",exhibitionId);

        return R.success(baseService.queryExhibitionMaterialByExhibitionId(exhibitionId,id));
    }

    /**
     * 删除材料申报记录
     * @param id
     * @return
     */
    @ApiOperation(value = "删除材料申报记录", notes = "删除材料申报记录")
    @SysLog("删除材料申报记录")
    @GetMapping("/removeExhibitionMaterial")
    public R<Boolean> removeExhibitionMaterial(@RequestParam("id") @Validated @NotNull(message = "上传记录关系表ID必填") Long id) {
        log.info("removeExhibitionMaterial - 删除材料申报记录   id: {}",id);
        // 软删
        ExhibitionMaterial updateEntity = new ExhibitionMaterial();
        updateEntity.setId(id);
        updateEntity.setIsDeleted(BusinessConstant.YES);
        return R.success(exhibitionMaterialService.updateById(updateEntity));
    }


    /**
     * 上传材料申报附件
     * @param attachmentFileDTO attachmentFileDTO
     * @return R<Boolean>
     */
    @ApiOperation(value = "上传材料申报附件", notes = "上传材料申报附件")
    @SysLog("上传材料申报附件")
    @PostMapping("/uploadAttachmentFile")
    @Transactional(rollbackFor = Exception.class)
    public R<Boolean> uploadAttachmentFile(@RequestBody AttachmentFileDTO attachmentFileDTO) {
        log.info("uploadAttachmentFile - 上传材料申报附件   attachmentFileDTO: {}",attachmentFileDTO);
        // 如果存在先删除
        AttachmentFileDTO deleteDTO = new AttachmentFileDTO();
        deleteDTO.setBusinessId(attachmentFileDTO.getBusinessId());
        deleteDTO.setBusinessType(VenueBookingMoudleEnum.EXHIBITION_MATERIAL.getCode());
        R<List<AttachmentFileVO>> listR = attachmentFileFeign.queryAttachmentFile(deleteDTO);
        if(Objects.nonNull(listR) && CollectionUtils.isNotEmpty(listR.getData())){
            for (AttachmentFileVO datum : listR.getData()) {
                attachmentFileFeign.detele(datum.getId());
            }
        }
        // 保存新的
        ExhibitionMaterial updateEntity = new ExhibitionMaterial();
        updateEntity.setId(attachmentFileDTO.getBusinessId());
        updateEntity.setAttamentUrl(attachmentFileDTO.getAttachmentUrl());
        attachmentFileDTO.setBusinessType(VenueBookingMoudleEnum.EXHIBITION_MATERIAL.getCode());
        attachmentFileFeign.addAttachmentFile(Collections.singletonList(attachmentFileDTO));
        return R.success(exhibitionMaterialService.updateById(updateEntity));
    }


    /**
     * 绑定展会～材料申报
     *
     * @param exhibitionMaterialSaveDTO 绑定展会～材料申报
     * @return R<Long>
     */
    @ApiOperation(value = "绑定展会～材料申报", notes = "绑定展会～材料申报")
    @PostMapping("/addExhibitionMaterial")
    public R<Long> addExhibitionMaterial(@RequestBody @Validated(ExhibitionMaterialSaveDTO.Check.class) ExhibitionMaterialSaveDTO exhibitionMaterialSaveDTO) {
        log.info("addExhibitionMaterial - 绑定展会～材料申报   exhibitionMaterialSaveDTO: {}",exhibitionMaterialSaveDTO);
        return success(baseService.addExhibitionMaterial(exhibitionMaterialSaveDTO));
    }

}
